import { Result } from 'ant-design-vue';
import type { RouteRecordRaw } from 'vue-router';
import RouterView from '@/layout/routerView/index.vue';
import { isUrl } from '@/framework/utils/is';
import { uniqueSlash } from '@/framework/utils/urlUtils';
import { constantRouterComponents } from '@/router/asyncModules';
import common from '@/router/staticModules';
import router, { routes } from '@/router';
import NotFound from '@/pages/error/404.vue';
import { errorRoute, notFound } from './staticModules/error';
import { REDIRECT_ROUTE } from './staticModules/besidesLayout';
import type { PermissionType } from '@/framework/core/permission/modules/types';
import outsideLayout from './outsideLayout';
import { modulesRoutes } from './localModules';
import { useModulesViewStore } from '@/store/modules/moduleView';
import { includes } from 'lodash-es';
import { singleModuleMenu } from '../modules/layout';
// 需要放在所有路由之后的路由
const endRoutes: RouteRecordRaw[] = [REDIRECT_ROUTE, errorRoute, notFound];

export function filterAsyncRoute(routes: API.Menu[], parentRoute: API.Menu | null = null, lastNamePath: string[] = []): RouteRecordRaw[] {
  return routes
    .filter((item) => item.type !== 2 && item.isShow && item.parentId == parentRoute?.id)
    .map((item) => {
      const { router, viewPath, name, icon, keepalive } = item;
      let fullPath = '';
      const pathPrefix = lastNamePath.slice(-1)[0] || '';
      if (isUrl(router)) {
        fullPath = router;
      } else {
        fullPath = router.startsWith('/') ? router : '/' + router;
        fullPath = router.startsWith(pathPrefix) ? fullPath : pathPrefix + fullPath;
        fullPath = [...new Set(uniqueSlash(fullPath).split('/'))].join('/');
      }
      let realRoutePath = router;
      if (parentRoute) {
        if (fullPath.startsWith(parentRoute?.router)) {
          realRoutePath = fullPath.split(parentRoute.router)[1];
        } else if (!isUrl(parentRoute.router) && !isUrl(router)) {
          realRoutePath = router;
        }
      }
      realRoutePath = realRoutePath.startsWith('/') ? realRoutePath.slice(1) : realRoutePath;
      const route: Partial<RouteRecordRaw> = {
        path: realRoutePath,
        // name: `${viewPath ? toHump(viewPath) : fullPath}-${item.id}`,
        name: fullPath,
        meta: {
          title: name,
          perms: [],
          icon: icon,
          namePath: lastNamePath.concat(fullPath),
          keepAlive: keepalive,
        },
      };

      if (item.type === 0) {
        // 如果是目录
        const children = filterAsyncRoute(routes, item, lastNamePath.concat(fullPath));
        if (children?.length) {
          route.component = RouterView;
          route.children = children;
          route.redirect = { name: children[0].name };
        } else {
          route.component = <Result status='500' title={name} sub-title='目录类型菜单不是真实页面，请为当前目录添加页面级子菜单或更改当前菜单类型.' />;
        }
        return route;
      } else if (item.type === 1) {
        // 如果是页面
        const Component = constantRouterComponents[viewPath] || NotFound;
        route.component = Component;

        const perms = routes.filter((n) => n.parentId === item.id).flatMap((n) => n.perms?.split(','));
        if (route.meta && perms) {
          // 设置当前页面所拥有的权限
          route.meta.perms = perms as PermissionType[];
        }
        return route;
      }
      return undefined;
    })
    .filter((item): item is RouteRecordRaw => !!item);
}

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (asyncMenus: API.Menu[]) => {
  try {
    // console.log('asyncMenus', asyncMenus);
    const routeList = filterAsyncRoute(asyncMenus);
    const layout = routes.find((item) => item.name == 'Layout')!;
    // console.log(routeList, '根据后端返回的权限路由生成');
    // 给公共路由添加namePath
    generatorNamePath(common);
    const menus = [...common, ...routeList, ...endRoutes];
    layout.children = menus;
    const removeRoute = router.addRoute(layout);
    // 获取所有没有包含children的路由，上面addRoute的时候，vue-router已经帮我们拍平了所有路由
    const filterRoutes = router.getRoutes().filter((item) => !item.children.length && !outsideLayout.some((n) => n.name === item.name));
    // 清空所有路由
    removeRoute();
    layout.children = [...filterRoutes];
    // 重新添加拍平后的路由
    router.addRoute(layout);
    // console.log("所有路由", router.getRoutes());

    return {
      menus: menus,
      routes: layout.children,
    };
  } catch (error) {
    console.error('生成路由时出错', error);
    return {
      menus: [],
      routes: [],
    };
  }
};

// export function filterLocalRoute(routes:RouteRecordRaw[], funcs:API.FuncInfo[]):RouteRecordRaw[] {
//   routes.forEach(route=>{
//     for(let i=0;i<funcs.length;i++){
//       if(route.m)
//     }
//   })
// }

export const generateMenu = (funcs: API.FuncInfo[]) => {
  try {
    /**
     * 处理模块路由顺序
     */
    const menuOrder: { [str: string]: any } = {};
    const sortMenu = [...singleModuleMenu];
    sortMenu.reverse().forEach((item, index) => {
      menuOrder[item] = index + 1;
    });
    modulesRoutes.sort((a, b) => {
      const bIndex = menuOrder[b.meta?.moduleName!] || 0;
      const aIndex = menuOrder[a.meta?.moduleName!] || 0;
      return bIndex - aIndex;
    });

    /**
     * 处理模块路由顺序，和上面不同的是：该方法只会显示配置在singleModuleMenu中的模块
     */
    // modulesRoutes = singleModuleMenu.flatMap(moduleName => {
    //   return modulesRoutes.filter(i => {
    //     return i.meta?.moduleName == moduleName
    //   })
    // })

    /**
     * funcs处理
     */
    const allFuncs = funcs?.reduce((pre, cur) => {
      pre?.push(cur);
      pre?.push(...cur?.children);
      return pre;
    }, []);
    let nameList = allFuncs && allFuncs.map((item) => item?.name);
    if (nameList?.includes('input_manage') || nameList?.includes('input_record') || nameList?.includes('sampleTraceability')) {
      allFuncs?.push({ name: 'input_manage_detail' });
    }
    if (nameList?.includes('out_manage') || nameList?.includes('out_record') || nameList?.includes('sampleTraceability')) {
      allFuncs?.push({ name: 'out_manage_detail' });
    }
    if (nameList?.includes('inventoryCount') || nameList?.includes('inventoryRecords')) {
      allFuncs?.push({ name: 'inventoryCountDetail' });
    }
    if (nameList?.includes('sampleSharing')) {
      allFuncs?.push({ name: 'sampleSharingOut' });
    }
    const layout = routes.find((item) => item.name == 'Layout')!;
    // 给公共路由添加namePath
    generatorNamePath(common);
    generatorNamePath(modulesRoutes);
    const menus = [...common, ...modulesRoutes, ...endRoutes];
    layout.children = menus;
    const removeRoute = router.addRoute(layout);
    // 获取所有没有包含children的路由，上面addRoute的时候，vue-router已经帮我们拍平了所有路由

    const filterRoutes = router
      .getRoutes()
      .filter((item) => !item.children.length && !outsideLayout.some((n) => n.name === item.name))
      .filter((item) => !allFuncs?.length || allFuncs?.some((n) => n?.name === item?.name)); // 权限区分
    // 清空所有路由
    removeRoute();
    layout.children = [...filterRoutes, ...common, ...endRoutes];

    /**
     * 缺失路由添加
     */
    // 重新添加拍平后的路由
    router.addRoute(layout);
    const commonMenu = ['home'];
    const moduleStore = useModulesViewStore();
    let filterMenu = menus
      .filter((item) => moduleStore.curModuleName === 'default' || (item.meta?.moduleName && includes(moduleStore.curModule?.modules, item.meta.moduleName)))
      .filter((item) => !allFuncs.length || allFuncs.some((n) => n.name === item.name) || commonMenu.includes(item.name)); // 权限区分

    /** 子系统menu排序 */
    /** 只支持menu一层children过滤 */
    filterMenu.forEach((menu) => {
      if (menu.children && menu.children.length) {
        menu.children = menu.children.filter((m) => !allFuncs.length || allFuncs.some((n) => n.name === m.name));
      }
    });
    moduleStore.curModuleName !== 'default' &&
      (filterMenu =
        moduleStore.curModule?.modules?.flatMap((moduleName) => {
          return filterMenu.filter((i) => {
            return i.meta?.moduleName == moduleName;
          });
        }) || []);

    return {
      menus: filterMenu,
      routes: layout.children,
    };
  } catch (error) {
    console.error('生成路由时出错', error);
    return {
      menus: [],
      routes: [],
    };
  }
};

/**
 * 主要方便于控制a-menu的open-keys，即控制左侧菜单应当展开哪些菜单
 * @param {RouteRecordRaw[]} routes 需要添加namePath的路由
 * @param {string[]} namePath
 */
export const generatorNamePath = (routes: RouteRecordRaw[], namePath?: string[], parent?: RouteRecordRaw) => {
  routes.forEach((item) => {
    if (item.children?.length) {
      if (item.meta && typeof item.name === 'string') {
        item.meta.namePath = Array.isArray(namePath) ? namePath.concat(item.name) : [item.name];
        item.meta.fullPath = parent?.meta?.fullPath ? [parent.meta.fullPath, item.path].join('/') : item.path;
        item.meta.fullPath = uniqueSlash(item.meta.fullPath);
        generatorNamePath(item.children, item.meta.namePath, item);
      }
    } else {
      if (item.meta && typeof item.name === 'string') {
        item.meta.namePath = Array.isArray(namePath) ? namePath.concat(item.name) : [item.name];
        item.meta.fullPath = parent?.meta?.fullPath ? [parent.meta.fullPath, item.path].join('/') : item.path;
        item.meta.fullPath = uniqueSlash(item.meta.fullPath);
      }
    }
  });
};
